/**
 * @angular 管理员
 * @description
 * @auth yang li
 */

film = function ($scope, $ducTools, $compile,$get, http, $dataTableSet){
    'use strict';
    var filmTable = $('#filmTable').DataTable({
        sAjaxSource: 'basic/get_films_info',
		fnServerData:  $ducTools.retrieveData,
        fnServerParams: function (aoData) {
            aoData.push(
                { "name": "filmCode", "value": $scope.filmCode},
				{ "name": "releaseType", "value": $scope.releaseType},
                { "name": "releaseStartTime", "value": $("#releaseStartTime").val()},
				{ "name": "releaseEndTime", "value": $("#releaseEndTime").val()}
            )
        },
        columns: [
            {"data": "name"},
			{"data": "language"},
            {"data": "duration"},
			{"data": "size"},
			{"data": "dimensional"},
            {"data": "showTime"},
            {"data": null},
            {"data": "releaseTime"},
			{"data": null},
        ],
     	columnDefs: [
            {
                targets: 6,
                render: function (c) {
					if(c.releaseType == "0"){
						return "下架";		
					}else if(c.releaseType == "1"){
						return "未发布";	
					}else if(c.releaseType == "2"){
						return "已发布";	
					}
                }
            },
			{
                targets: 8,
                render: function (c) {
					
					if(c.releaseType == "0"){
						return "<button class='btn btn-success btn-xs' ng-click=showDetail('"+c.filmCode+"')> 查看/编辑详细信息 </button> &nbsp;" + 
								"<button class='btn btn-info btn-xs' ng-click=releaseFilm('"+c.filmCode+"','2')> 发布 </button>";		
					}else if(c.releaseType == "1"){
						return "<button class='btn btn-success btn-xs' ng-click=showDetail('"+c.filmCode+"')> 查看/编辑详细信息 </button> &nbsp;" + 
								"<button class='btn btn-info btn-xs' ng-click=releaseFilm('"+c.filmCode+"','2')> 发布 </button> &nbsp;" +
								"<button class='btn btn-success btn-xs' ng-click=releaseFilm('"+c.filmCode+"','0')> 下架 </button>" ;		
					}else if(c.releaseType == "2"){
						return "<button class='btn btn-success btn-xs' ng-click=showDetail('"+c.filmCode+"')> 查看/编辑详细信息 </button> &nbsp;" + 
								"<button class='btn btn-info btn-xs' ng-click=releaseFilm('"+c.filmCode+"','1')> 取消发布 </button> &nbsp;" +
								"<button class='btn btn-success btn-xs' ng-click=releaseFilm('"+c.filmCode+"','0')> 下架 </button>" ;		
	
					}
					
					
                }
            }
        ],
        createdRow: function( row, data, dataIndex ) {
            $compile(row)($scope);
        }
    });

    $dataTableSet.dataTableRowShow('filmTable');
	setTimeout(function(){
		$get.selectTwo("#filmCode");		
	},200);

    $scope.accountRecordDraw = function() {
        filmTable.draw();
    };
	
	//影片名称
	http.post({}, 'schedule/get_film').then(function (data) {
        $scope.filmList = data;
    });
	
	//删除演员
	$scope.detailEach = function(actorId,index){
		//alert(index);
		swal({
			title: "确定要删除吗？",
			showCancelButton: true,
			closeOnConfirm: false,
			confirmButtonText: "确定",
			confirmButtonColor: "#046dae",
			cancelButtonText: "取消",
			animation: "slide-from-top"
		},function () {
			http.post({"actorId":actorId}, 'basic/delete_film_actors').then(function(data) {
				swal("删除成功！");	
				$scope.actorList.splice(index, 1);
			});        
		});
	}
	
	//删除剧照
	$scope.detailStage = function(pictureId,index){
		swal({
			title: "确定要删除吗？",
			showCancelButton: true,
			closeOnConfirm: false,
			confirmButtonText: "确定",
			confirmButtonColor: "#046dae",
			cancelButtonText: "取消",
			animation: "slide-from-top"
		},function () {
			http.post({"pictureId":pictureId}, 'basic/delete_film_posts').then(function (data) {
				swal("删除成功！");		
				$scope.stageList.splice(index, 1);
			});        
		});
	}
	
	//发布，下架
	$scope.releaseFilm = function(filmCode,releaseType){
		var tipsTitle = "";
		if(releaseType == "0"){
			tipsTitle = "你确定要下架该影片吗？";	
		}else if(releaseType == "1"){
			tipsTitle = "你确定要取消发布该影片吗？";	
		}else if(releaseType == "2"){
			tipsTitle = "你确定要发布该影片吗？";	
		}
		swal({
			title: tipsTitle,
			showCancelButton: true,
			closeOnConfirm: false,
			confirmButtonText: "确定",
			confirmButtonColor: "#046dae",
			cancelButtonText: "取消",
			animation: "slide-from-top"
		},function () {
        	http.post({"filmCode":filmCode,"releaseType":releaseType}, '/basic/release').then(function (data) {
				swal("成功！");		
				filmTable.draw();
			});        
        });
	}
	
	//新增演员
	$scope.addActor = function(){
		var actorLength = $("#actorList tr").length;
		var newIndex = actorLength + 1;
		var id = "actorUpload"+newIndex;
		if(actorLength >= 30){
			swal("最多只能添加30名演员！");
			return;	
		}
		var html = $compile("<tr class='patTr' val=''>"
				    + "<td><input type='text' class='orderNum textIn' /></td>"
					+ "<td><input type='text' class='actorInfo textIn' /></td>"
					+ "<td><input type='text' class='roleInfo textIn' /></td>"
					+ "<td>"
					+		"<div class='fileupload-new thumbnail'>"
					+			"<input name='actorUpload"+newIndex+"' type='text' class='imgInput'/>"
					+			"<img id='actorUpload"+newIndex+"' class='imgUpload' src='/images/no-pic.png' alt=''>"
					+		"</div>"
					+	"</td>"
					+	"<td>"
					+	"<input type='text' class='markInfo textIn' /></td>"
					+	"<td><button class='btn btn-info btn-xs deleteFileUpload'> 删除 </button></td>"
					+"</tr>")($scope);
		$("#actorList").append(html);
		initUploaders(id);
		$(".deleteFileUpload").on("click",function(){
			$(this).parents("tr.patTr").remove();		
		});
	}

	//剧照
	$scope.addStage = function(){
		var stageLength = $("#stageMain .thumbnail").length;
		var newIndex = stageLength + 1;
		var id = "stagePhoto1"+newIndex;
		var html = $compile("<div class='fileupload-new thumbnail addNew' val=''>"
                            + "<input name='stagePhoto"+newIndex+"' type='text' class='imgInput'/>"
                            + "<img id='stagePhoto1"+newIndex+"' class='imgUpload' src='/images/no-pic.png' alt=''>"
                            + "<button class='btn btn-info btn-xs deleteStage'> 删除 </button>"
                        + "</div>")($scope);
		$("#stageMain").append(html);
		initUploaders(id);
		$(".deleteStage").on("click",function(){
			$(this).parents(".thumbnail").remove();		
		});
	}
	
	//详情
	$scope.showDetail = function(filmCode) {
        $("#showDetail").modal('show');
		$scope.filmDetail = "";
		$scope.filmType = "";
		$scope.showTime = "";
		$scope.country = "";
		$scope.releaseCompany = "";
		$scope.filmScore = "";
		$scope.introduction = "";
		$scope.filmType = "";
		$scope.director = "";
		$scope.actorList = "";
		$scope.stageList = "";
		
		//详情
        http.post({"filmCode":filmCode}, "basic/get_film_details").then(function(data) {
			$scope.filmDetail = data[0];
			$scope.filmType = data[0].filmType;
			$scope.showTime = $("#showTime").val(data[0].showTime);
			$scope.country = data[0].country;
			$scope.releaseCompany = data[0].releaseCompany;
			$scope.filmScore = data[0].filmScore;
			$scope.introduction = data[0].introduction;
			$scope.filmType = data[0].filmType;
			$scope.director = data[0].director;
			$scope.actorList = data[0].filmActorsViewList;
			$scope.stageList = data[0].filmPostsViewList;
        })
		
		setTimeout(function(){
			for(var j = 0; j < $scope.actorList.length; j++){
				var id = $("#actorList").find("tr").eq(j).find("img").attr("id");
				console.log(id);
				initUploaders(id);
			}
			for(var k = 0; k < $scope.stageList.length; k++){
				var id = $("#stageMain").find("img").eq(k).attr("id");
				console.log(id);
				initUploaders(id);
			}
		},1000);
		
    }
	
	$scope.updateDetail = function(filmCode){
		var actorList = [];
		var stageList = [];
		for(var i=0; i < $("#actorList tr").length; i ++){
			var actorId = $("#actorList tr").eq(i).attr("val");
			var orderId = $("#actorList tr").eq(i).find(".orderNum").val();	
			var roleName = $("#actorList tr").eq(i).find(".actorInfo").val();	
			var role = $("#actorList tr").eq(i).find(".roleInfo").val();	
			var message = $("#actorList tr").eq(i).find(".markInfo").val();	
			var roleUrl = $("#actorList tr").eq(i).find(".imgUpload").attr("src");
			var actorListEach = {
				filmCode : 	filmCode,
				actorId : 	actorId,
				orderId : 	orderId,
				roleName : 	roleName,
				message : 	message,
				roleUrl : 	roleUrl,
				role:role,
			};
			actorList.push(actorListEach);	
		}
		
		for(var i=0; i < $("#stageMain .thumbnail").length; i ++){
			var pictureId = $("#stageMain .thumbnail").eq(i).attr("val");
			var pictureUrl = $("#stageMain .thumbnail").eq(i).find(".imgUpload").attr("src");
			var stageListEach = {
				filmCode : 	filmCode,
				pictureId : 	pictureId,
				pictureUrl : 	pictureUrl,
			};
			stageList.push(stageListEach);	
		}
		
		http.post(JSON.stringify({
			"filmCode":filmCode,
			"filmType":$("#filmType").val(),
			"showTime":$("#showTime").val(),
			"country":$("#country").val(),
			"releaseCompany":$("#releaseCompany").val(),
			"filmScore":$("#filmScore").val(),
			"introduction":$("#introduction").val(),
			"director":$("#director").val(),
			"directorPicture":$("#imgUpload1").attr("src"),
			"filmActorsViewList":actorList,
			"filmPostsViewList":stageList,
			"poster":$("#poster").attr("src"),
			"bigPoster":$("#bigPoster").attr("src"),
		}), "basic/save_film_details","application/json").then(function(data) {
			$("#showDetail").modal('hide');
			swal("保存成功！");
			$("#actorList tr.patTr").remove();
			$("#stageMain .addNew").remove();	
        },"json")		
    }
		
	//图片上传
	//var uploaders = [];
	function initUploaders(id) {
	   //for(var i =0; i < uploaders.length; i++){
            var button = id;
            var uploader = new plupload.Uploader({
                runtimes : 'html5,flash,silverlight,html4',
                browse_button : button,
                container : document.getElementById('filmDetailInfo'),
                url : serverUrl + 'upload/fileUpload',
                multipart:true,
                multi_selection:true,
                filters : {
                    //max_file_size : '200kb',
                    mime_types : [{
                        title : "Image files",
                        extensions : "jpg,gif,png,bmp"
                    }]
                },
                init: {
                    FilesAdded: function(uploader,files){
						for (var i = 0, len = files.length; i < len; i++) {
							var file_size = files[i].size;
							if(file_size > 204800){
								swal("文件上传上限为200KB，请重新选择！");
							}else{
								uploader.start();				
							}
						}
                    },
                    FileUploaded : function(uploader, files, responseObject){
						$("input[name='"+ button +"']").val(JSON.parse(responseObject.response).url);
						$("#" + button).attr("src", JSON.parse(responseObject.response).url);
						$("#companyDepositoryErrorMsg label").hide();	
                    }
                }
            });
            uploader.init();
			//alert(id);
        };
    //}
    //initUploaders('actorUpload1');
	initUploaders('imgUpload1');
	initUploaders('stagePhoto1');
	initUploaders('poster');
	initUploaders('bigPoster');
};
